﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Drawing;
using System.Drawing.Imaging;

namespace TotalVisitorsCounter
{
    public partial class VisitorsCounter : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Application["visitorsCount"] == null)
            {
                Application["visitorsCount"] = 0;
            }

            if (Request.Cookies["visited"]==null)
            {
                //COOKIE SHOULD NEVER EXPIRE. atm its until the browser is closed for testing reasons
                //THE COUNTER SHOULD BE IN DATABASE :)
                Response.Cookies.Add(new HttpCookie("visited"));
                Application["visitorsCount"] = 1 + (Application["visitorsCount"] as int?);
            }
            GeneratePicture();            
        }

        private void GeneratePicture()
        {
            Bitmap bitmap = new Bitmap(170, 50);
            Graphics drawer = Graphics.FromImage(bitmap);
            SolidBrush fill = new SolidBrush(Color.Purple);
            SolidBrush background = new SolidBrush(Color.Cyan);
            drawer.FillRectangle(background, 0, 0, bitmap.Width, bitmap.Height);
            drawer.DrawString("Visitors: " + Application["visitorsCount"], new Font(FontFamily.GenericMonospace, 13), fill, new PointF(20f, 20f));
            Response.Clear();
            Response.ContentType = "image/gif";
            bitmap.Save(Response.OutputStream, ImageFormat.Gif);
        }
    }
}